package main

import (
	"fmt"
	"net"
	"strings"
)

type User struct {
	Name string
	Addr string
	//当前某个用户接收msg的channel
	C chan string
	//客户端与服务端之间的tcp连接
	conn net.Conn

	server *Server
}

// NewUser 新建用户
func NewUser(conn net.Conn, server *Server) *User {
	userAddr := conn.RemoteAddr().String()
	user := &User{
		Name:   userAddr,
		Addr:   userAddr,
		C:      make(chan string),
		conn:   conn,
		server: server,
	}
	//监听自己的channel,有则通过tcp连接发送出去
	go user.ListenMessage()
	return user
}

// ListenMessage 监听当前chan
func (u *User) ListenMessage() {
	for {
		msg := <-u.C
		u.SendMsg(msg)
	}
}

// Online 用户上线
func (u *User) Online() {
	u.server.mapLock.Lock()
	u.server.OnlineMap[u.Name] = u
	u.server.mapLock.Unlock()
	//广播
	u.DoMessage("上线")
}

// Offline 用户下线
func (u *User) Offline() {
	u.server.mapLock.Lock()
	delete(u.server.OnlineMap, u.Name)
	u.server.mapLock.Unlock()
	//广播
	u.DoMessage("下线")
}

// DoMessage 给用户发送信息
func (u *User) DoMessage(msg string) {
	if msg == "who" {
		//查询在线人数
		u.server.mapLock.RLock()
		for _, user := range u.server.OnlineMap {
			onlineMsg := "[" + user.Addr + "]" + user.Name + ":正在线上中..."
			u.SendMsg(onlineMsg)
		}
		u.server.mapLock.RUnlock()
	} else if len(msg) > 7 && msg[:7] == "rename|" {
		//修改用户名 格式:rename|XXX
		splitStr := strings.Split(msg, "|")
		newName := splitStr[1]
		u.server.mapLock.Lock()
		//判断newName是否已存在
		if u.server.OnlineMap[newName] != nil {
			fmt.Println(newName, "的名称已存在无法修改")
			u.SendMsg(newName + "的名称已存在无法修改")
		} else {
			delete(u.server.OnlineMap, u.Name)
			u.Name = newName
			u.server.OnlineMap[u.Name] = u
			u.server.mapLock.Unlock()
			fmt.Println(u, "修改名称成功,新名称为:", newName)
			u.SendMsg("修改名称成功,新名称为:" + newName)
		}
	} else if len(msg) > 4 && msg[:3] == "to|" {
		//私聊功能(to|userName|msg) 表示当前用户对某个userName的用户发送msg
		splitStr := strings.Split(msg, "|")
		toUserName := splitStr[1]
		toMsg := splitStr[2]
		if len(toUserName) == 0 || len(toMsg) == 0 {
			u.SendMsg("当前私聊格式错误，请遵循:to|userName|XXX")
			fmt.Println(u.Name + "请求私信错误")
			return
		}
		u.chatPrivate(toUserName, toMsg)
	} else {
		u.server.BroadCast(u, msg)
	}
}

// SendMsg 给当前user发送信息给客户端
func (u *User) SendMsg(msg string) {
	_, err := u.conn.Write([]byte(msg + "\n"))
	if err != nil {
		return
	}
}

// ChatPrivate 给指定某个user发送信息
func (u *User) chatPrivate(toUserName, msg string) {
	m := u.Name + " send to you:" + msg
	fmt.Println(m)
	u.server.mapLock.RLock()
	toUser, ok := u.server.OnlineMap[toUserName]
	if ok {
		toUser.C <- m
	} else {
		u.SendMsg("您想要私信的 " + toUserName + " 用户不存在")
	}
	u.server.mapLock.RUnlock()
}
